package com.privasphere.wikidoclet.doclet;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.AttributesImpl;

import com.privasphere.wikidoclet.doclet.page.IndexPage;
import com.privasphere.wikidoclet.doclet.page.Page;
import com.privasphere.wikidoclet.util.WikiDocletCfg;

/**
 * The PageWriter class is used to write the Pages to an XML File. The Class
 * uses the Properties loaded in the WikiDocletCfg to find the location to write
 * the File to.
 * 
 * @author Rolf
 * @version 1.0
 * 
 */
class PageWriter {

	private static Logger logger = LoggerFactory.getLogger(WikiDoclet.class);

	/**
	 * Write a List of Pages to the XML File
	 * 
	 * @param pageList
	 *            A List<Page> Object
	 * @param XmlFilePath
	 *            Full path to an XML File
	 */
	public void writePagesToXml(List<Page> pageList, String XmlFilePath) {
		File f = new File(XmlFilePath);
		// Create Folders if Required
		if (f.getParent() != null) {
			new File(f.getParent()).mkdirs();
		}
		
		// Create all IndexPage Entries
		AttributesImpl a = new AttributesImpl();
		for (Page s : pageList) {
			if (s instanceof IndexPage) {
				((IndexPage) s).index(pageList);
				
				a.addAttribute("", WikiDocletCfg.WIKI_DOCLET_INDEX_PAGE_NAME_ATTRIBUTE, "", "", s.getPageTitle());
			}
		}
		
		try {
			// Create Filewriter
			FileWriter f0 = new FileWriter(f);
			// Create new XML
			XMLWriterHandler xmlwriter = new XMLWriterHandler(f0);
			// Start XML Document
			xmlwriter.startDocument();
			// Root Node
		
			
			xmlwriter.startElement("", WikiDocletCfg.WIKI_DOCLET_XML_ROOT, "", a);

			// Create Page Entry for each PAge
			for (Page s : pageList) {
				logger.debug("Writing Page " + s.getPageTitle());
				xmlwriter.startElement(WikiDocletCfg.WIKI_DOCLET_XML_PAGE);
				xmlwriter.dataElement(WikiDocletCfg.WIKI_DOCLET_XML_TITLE, s.getPageTitle());
				xmlwriter.dataElement(WikiDocletCfg.WIKI_DOCLET_XML_CONTENT, s.toString());
				xmlwriter.dataElement(WikiDocletCfg.WIKI_DOCLET_XML_HASH, s.getHash());
				xmlwriter.dataElement(WikiDocletCfg.WIKI_DOCLET_XML_TIME, new Date().getTime() + "");

				xmlwriter.endElement(WikiDocletCfg.WIKI_DOCLET_XML_PAGE);
			}
			// Close Root Node
			xmlwriter.endElement(WikiDocletCfg.WIKI_DOCLET_XML_ROOT);
			// Close XML Document
			xmlwriter.endDocument();
		} catch (IOException e) {
			logger.error("XML File could not be written.", e);
		} catch (SAXException e) {
			logger.error("XML File could not be written.", e);
		}
	}
}
